# -*- coding: utf-8 -*-
#
import os
from google.appengine.api import rdbms
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from tsbase import *
from tsmodel import *

class Error(baseHandler):
    def get(self):
        return self.render('template/404.html', {})

class getppic(baseHandler):
    def get(self,id):
        pic = memcache.get('prodpic'+ str(id))
        if not pic:
            pic = prodpic.get_by_id(int(id))
        if not pic:
            return self.error(404)
        memcache.set('prodpic'+ str(id), pic, 864000)
        self.header('Content-Type', str(pic.mime))
        self.header('Cache-Control', "max-age=315360000")
        self.header('Last-Modified', gmt_date(pic.cre8time))
        self.write(pic.fbin)

class front_page(baseHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            acc = admin.all().filter('email =', user.email().lower()).get()
            if acc and acc.role:
                return self.redirect(acc.role.tpurl)
        return self.redirect("/index")

class company_page(baseHandler):
    def get(self):

        user = users.get_current_user()
        if user:
            self.me = admin.all().filter('email =', user.email().lower()).get()
            userinfo = (u"<span>%s</span> | <a href=\"%s\">退出登录</a>" %
                    ( self.me.name, users.create_logout_url("/") ) )
        else:
            return self.redirect("/index")

        self.mystore = self.me.refcstore

        template_values={"userinfo": userinfo,
            'mystore':self.mystore,
            "app_id": APP_ID}

        self.render('template/tstore.html', template_values)
class cn003bbs_page(baseHandler):
    def make_cookie_header(self,cookie):
        ret = ""
        for val in cookie.values():
            ret += "%s=%s; " % (val.key, val.value)
        return ret

    @requires_auth
    def get(self):
        from google.appengine.api import urlfetch

        jumpurl = "http://www.gztiens.com/bbs/read.php?tid=12768"
        cn003cookie = memcache.get('cn003cookie')
        if not cn003cookie:
            import urllib,Cookie
            loginurl = "http://www.gztiens.com/bbs/login.php?"
            form_data = urllib.urlencode({"pwuser":"user", "pwpwd":"password","submit":"登录", "hideid":"0", "lgt":"0", "cktime":"31536000", "forward":'', "step":"2", "jumpurl":jumpurl})
            try:
                result = urlfetch.fetch(
                    url = loginurl,
                    payload=form_data,
                    method=urlfetch.POST,
                    headers={
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.4.2.80 Safari/525.13'
                        },
                    follow_redirects = False
                    )
                if result.status_code == 200:
                    cn003cookie = self.make_cookie_header(Cookie.SimpleCookie(result.headers.get('set-cookie', '')))
                    memcache.set('cn003cookie', cn003cookie, 2160000)#25d
            except:
                return self.redirect("/tsgz")

        try:
            result = urlfetch.fetch(
                url = jumpurl,
                method=urlfetch.GET,
                headers={
                    'Cookie':cn003cookie,
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.4.2.80 Safari/525.13'
                    },
                follow_redirects = False
                )
            if result.status_code == 200:
                result = result.content.decode('gbk').encode('utf-8')
                ps = re.search(r'\<div class=\"f14\" id=\"read_tpc\"\>.*\]\<\/div\>\<\/div\>', result)
                if ps:
                    self.write(ps.group(0))
        except:
            return self.redirect("/tsgz")

class store_page(baseHandler):
    @requires_auth
    def get(self):

        user = users.get_current_user()
        if user:
            self.me = admin.all().filter('email =', user.email().lower()).get()
        else:
            return self.redirect("/index")

        self.mystore = self.me.refcstore
        optcmpny = memcache.get('optcmpny')#self.me.refcstore
        optstore = memcache.get('optstore')#self.me.refcstore
        if (not optcmpny) or (not optstore):
            def cbcstore (cs):
                return cs.type == 'cb'
            def aacstore (cs):
                return cs.type == 'aa'
            optcstore = cstore.all().filter('type IN', ['cb', 'aa']).fetch(1000)
            optcmpny = filter(cbcstore, optcstore)
            optstore = filter(aacstore, optcstore)
            memcache.set('optcmpny', optcmpny, 2548800)#29.5d
            memcache.set('optstore', optstore, 2548800)

        userinfo = (u"<span>%s@%s</span> | <a href=\"%s\">退出登录</a>" %
                ( self.me.name, self.mystore.name, users.create_logout_url("/") ) )

        self.sales = getdata(sales, filters=[['applied =',False]], order=["-date"], limit=21)
        pvtypes = pubdata(pvtype, order=["-pvrate","-bvrate","code"])#pubpvtypes-pvrate-bvrate
        #pcls = pubdata(prodcls, order=["code"])#pubprodclscode

        template_values={"userinfo": userinfo,
            'isotime':(datetime.now()+timedelta(hours=+8)),
            'mystore':self.me.refcstore,
            'optcmpny':optcmpny,
            'optstore':optstore,
            'sales': self.sales,
            "pvtypes": pvtypes,
            #"pclass": pcls,
            'imgsurl':imagesurl,
            "app_id": APP_ID}

        self.render('template/tstore.html', template_values)
class guest_page(baseHandler):
    def get(self):

        user = users.get_current_user()
        if user:
            self.me = admin.all().filter('email =', user.email().lower()).get()
            userinfo = (u"<span>%s</span> | %s <a href=\"%s\">退出登录</a>" %
                    ( self.me.name if self.me else user.email(), u"<a href=\"/tiens\">管理</a> |" if self.me else "", users.create_logout_url("/") ) )
        else:
            userinfo = (u"<a href=\"%s\">用户登录</a>" % ( users.create_login_url('/') ) )

        template_values={"userinfo": userinfo,
            'isotime':(datetime.now()+timedelta(hours=+8)),
            'imgsurl':imagesurl,
            "app_id": APP_ID}

        self.render('template/tsindex.html', template_values)
class test_page(baseHandler):
    def get(self):

        user = users.get_current_user()
        if user:
            self.me = admin.all().filter('email =', user.email().lower()).get()
            userinfo = (u"<span>%s</span> | %s <a href=\"%s\">退出登录</a>" %
                    ( self.me.name if self.me else user.email(), u"<a href=\"/tiens\">管理</a> |" if self.me else "", users.create_logout_url("/") ) )
        else:
            userinfo = (u"<a href=\"%s\">用户登录</a>" % ( users.create_login_url('/') ) )

        template_values={"userinfo": userinfo,
            'isotime':(datetime.now()+timedelta(hours=+8)),
            'imgsurl':imagesurl,
            #'cloudrs':cloudrs,
            "app_id": APP_ID}

        self.render('template/test.html', template_values)

app = webapp.WSGIApplication(
        [
        ('/tscompany', company_page),
        ('/tstore', store_page),
        ('/index', guest_page),
        ('/tsgz', cn003bbs_page),
        ('/tp', test_page),
        ('/', front_page),
        (r'/pp/(?P<id>[0-9]+)/{0,1}', getppic),
        ('.*',Error),
        ],
        debug=True)
